<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <date-range-picker
        v-model="modelEndDate"
        clearable
        placeholder="下單時間"
        class="filter-item"
        :fix-date.sync="query.createTime"
        @keyup.enter.native="crud.toQuery"
      />
      <el-input
        v-model="query.orderSn"
        clearable
        placeholder="訂單編號"
        style="width: 185px;"
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
      />
      <el-input
        v-model="query.memberName"
        clearable
        placeholder="用戶姓名"
        style="width: 185px;"
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
      />
      <el-input
        v-model="query.receiverPhone"
        clearable
        placeholder="收貨人電話"
        style="width: 185px;"
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
      />
      <el-input
        v-model="query.receiverRegion"
        clearable
        placeholder="收货區域"
        style="width: 185px;"
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
      />
      <el-select
        v-model="query.deliveryType"
        placeholder="配送類型"
        clearable
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
        @change="crud.toQuery"
      >
        <el-option
          v-for="item in dict.deliveryType"
          :key="item.id"
          :label="item.dictValue"
          :value="item.dictKey"
        />
      </el-select>
      <el-select
        v-model="query.orderStatus"
        placeholder="訂單狀態"
        clearable
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
        @change="crud.toQuery"
      >
        <el-option
          v-for="item in dict.orderStatus"
          :key="item.id"
          :label="item.dictValue"
          :value="item.dictKey"
        />
      </el-select>
      <el-select
        v-model="query.paymentStatus"
        placeholder="付款狀態"
        clearable
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
        @change="crud.toQuery"
      >
        <el-option
          v-for="item in dict.paymentStatus"
          :key="item.id"
          :label="item.dictValue"
          :value="item.dictKey"
        />
      </el-select>
      <el-select
        v-model="query.preSale"
        placeholder="是否預售訂單"
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
        @change="crud.toQuery"
      >
        <el-option
          v-for="item in dict.presellState"
          :key="item.id"
          :label="item.dictValue"
          :value="item.dictKey"
        />
      </el-select>
      <el-select
        v-model="query.manualOrder"
        placeholder="訂單類型"
        class="filter-item"
        clearable
        @keyup.enter.native="crud.toQuery"
        @change="crud.toQuery"
      >
        <el-option
          v-for="item in dict.manualOrder"
          :key="item.id"
          :label="item.dictValue"
          :value="item.dictKey"
        />
      </el-select>

      <rrOperation :crud="crud" />
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <template #right>
          <el-button
            v-permission="permission.updateDeliveryTime"
            class="filter-item"
            size="mini"
            type="primary"
            :disabled="crud.selections.length !== 1"
            @click="showUpdateDeliveryTime(crud.selections)"
          >修改派送時間
          </el-button>
          <el-button
            v-permission="permission.complete"
            class="filter-item"
            size="mini"
            type="warning"
            :disabled="!crud.selections.length > 0"
            @click="complete(crud.selections)"
          >完成訂單
          </el-button>
          <el-button
            v-permission="permission.printDocuments"
            class="filter-item"
            size="mini"
            type="danger"
            :disabled="!crud.selections.length > 0"
            @click="printDocuments(crud.selections)"
          >打印備貨
          </el-button>
          <el-button
            v-permission="permission.updateOrderNote"
            class="filter-item"
            size="mini"
            type="info"
            :disabled="!crud.selections.length > 0"
            @click="flagComplaint(crud.selections)"
          >標記投訴
          </el-button>
          <el-button
            v-permission="permission.updateOrderNote"
            class="filter-item"
            size="mini"
            type="warning"
            :disabled="!crud.selections.length > 0"
            @click="exportDeliveryOrder(crud.selections)"
          >導出
          </el-button>
          <el-button
            v-if="query.preSale"
            v-permission="permission.preSalArrival"
            class="filter-item"
            size="mini"
            type="success"
            :disabled="!crud.selections.length > 0"
            @click="preSalArrival(crud.selections)"
          >預售到貨
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            @click="addOffLineOrder"
          >新增後台訂單
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="info"
            :disabled="!crud.selections.length > 0"
            @click="messageVisible = true"
          >发送站内信
          </el-button>
        </template>
      </crudOperation>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" />
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        style="width: 100%;"
        stripe
        :row-style="isRed"
        row-key="id"
        @selection-change="crud.selectionChangeHandler"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" />
        <el-table-column prop="orderMarkType" label="标记" width="60" min-width="40">
          <template
            v-if="dict.label.orderMarkType"
            slot-scope="scope"
          >
            <el-tooltip
              v-for="(item, index) in scope.row.orderMarkType"
              :key="index"
              class="item"
              effect="dark"
              :content="dict.dict.orderMarkType[item].remark || ''"
              placement="top-start"
            >
              <el-tag :type="selTagType(item)" style="margin-right: 5px" size="mini">
                {{ dict.label.orderMarkType[item] }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="orderSn" label="订单编号" sortable>
          <template slot-scope="scope">
            <div>{{ scope.row.orderSn }}</div>
            <el-tag
              v-if="scope.row.preSale"
              type="danger"
              style="margin-right: 5px;font-size: 12px"
              size="mini"
              effect="dark"
            >
              預售
            </el-tag>
            <el-tag
              v-if="scope.row.preSaleArrival"
              type="danger"
              style="margin-right: 5px;font-size: 12px"
              size="mini"
              effect="dark"
            >
              到貨
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentTime" label="支付时间" sortable min-width="110" />

        <el-table-column prop="actualDeliveryTime" label="配送时间" sortable min-width="130">
          <template slot-scope="scope">
            <div :class="scope.row.actualDeliveryTime === scope.row.deliveryTime ? '' :'DeliveryTime'">
              {{ scope.row.actualDeliveryTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="memberName" label="用户" :show-overflow-tooltip="true" />
        <el-table-column prop="payType" label="支付方式" sortable>
          <template slot-scope="scope">
            {{ payType(scope.row.payType) }}
          </template>
        </el-table-column>
        <el-table-column prop="payAmount" label="應付" sortable width="80" align="right" />
        <el-table-column prop="deliveryType" label="配送类型" sortable>
          <template slot-scope="scope">
            {{ dict.label.deliveryType[scope.row.deliveryType] }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="支付狀態" sortable>
          <template slot-scope="scope">
            {{ dict.label.paymentStatus[scope.row.paymentStatus] }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="100" sortable>
          <template slot-scope="scope">
            <el-tag
              v-if="dict.dict.orderStatus[scope.row.orderStatus]"
              :type="dict.dict.orderStatus[scope.row.orderStatus].cssClass"
            >{{ dict.label.orderStatus[scope.row.orderStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productNumber" label="數量" width="80">
          <template slot-scope="scope">
            <div style="font-size: 16px">
              {{ scope.row.productNumber }}
              <span style="font-size: 12px;">({{ scope.row.orderItems.length }}種)</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','order:edit','order:del'])" label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="primary" style="padding: 7px 10px;" size="mini" @click="orderDetails(scope.row.id)">view
            </el-button>
            <el-button
              type="danger"
              style="padding: 7px 10px;"
              size="mini"
              :disabled="scope.row.orderStatus>1"
              @click="onePrintDocuments(scope.row)"
            >print
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="buyerMemo" label="留言" :show-overflow-tooltip="true" width="50px">
          <template slot-scope="scope">
            <div>{{ scope.row.buyerMemo }}</div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog :visible="updateDeliveryTimeVisible" center width="30%" @close="updateDeliveryTimeVisible = false">
      <div class="dig">修改派送時間:
        <el-cascader
          v-model="updateDeliveryTime"
          :options="deliveryTimeOptions"
          :props="updateDeliveryTimeSetting"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDeliveryTimeVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateDelivery(crud.selections)">确 定</el-button>
      </span>
    </el-dialog>

    <div style="position: absolute; opacity:0;">
      <div v-for="(item, index) in printOrder" :id=" 'pdfWrap' + index" :key="index" class="print">
        <div class="invoice">
          <img src="../../../assets/images/Logo_white.png" height="74" width="250" class="invoiceImg" alt="">
          <div class="titleText">藍藍有限公司</div>
          <div class="titleText">客服 : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ item.phone }}</div>
          <div class="titleText">電郵 : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ item.email }}</div>
          <div class="titleText">地區 : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{
            item.receiverRegion
          }}
          </div>
          <div class="titleText">送貨時間 : &nbsp;&nbsp;&nbsp;{{ item.actualTimeSlot }}</div>
          <div style="margin-top:20px;height:20px;width:95%;border-top: 2px dashed black;" />
          <div class="single">單號: &nbsp; &nbsp; &nbsp; {{ item.orderSn }}</div>
          <div style="margin-top:20px;height:20px;width:95%;border-top: 2px dashed black;" />
          <div style="position:relative;height: 30px">
            <div class="positionLeft">商品名稱</div>
            <div class="positionRight">金額</div>
          </div>
          <div v-for="(cate, cateIndex) in item.map" :key="cateIndex" style="margin-bottom: 10mm">
            <div style="margin-bottom: 20px;width:95%;">
              <div style="height:10px;border-bottom: 2px dashed black;width:30%;float:left" />
              <div class="category">{{ cateIndex }}</div>
              <div style="height:10px;border-bottom: 2px dashed black;width:30%;float:right" />
            </div>
            <div
              v-for=" (products, productIndex) in cate"
              :key="productIndex"
              style="position: relative;height: 20px;margin-bottom: 25px;"
            >
              <div class="product positionLeft" style="width: 5cm">
                <div>{{ products.upc }} / {{ products.sku }} / {{ products.name }}</div>
                <div>{{ products.productQuantity }} @{{ products.price }}</div>
              </div>
              <div class="price positionRight">{{ products.totalAmount.toFixed(2) }}</div>
            </div>
          </div>

          <div style="margin-top:20px;height:10px;width:95%;border-top: 2px dashed black;" />
          <div style="height:20px;width:95%;border-top: 2px dashed black;" />

          <div style="position: relative;height: 15px">
            <div class="positionLeft">小計:</div>
            <div class="positionRight">{{ item.totalAmount.toFixed(2) }}</div>
          </div>
          <div v-if="item.freightAmount" style="position: relative;height: 15px">
            <div class="positionLeft">運費:</div>
            <div class="positionRight">{{ item.freightAmount.toFixed(2) }}</div>
          </div>
          <div v-if="item.bagFee" style="position: relative;height: 15px">
            <div class="positionLeft">膠袋費:</div>
            <div class="positionRight">{{ item.bagFee.toFixed(2) }}</div>
          </div>
          <div v-if="item.discountAmount" style="position: relative;height: 15px">
            <div class="positionLeft">優惠費用:</div>
            <div class="positionRight">{{ item.discountAmount.toFixed(2) }}</div>
          </div>

          <div style="position: relative;font-weight: bolder;height: 10px;margin-top: 15px">
            <div class="positionLeft">總結:</div>
            <div class="positionRight">{{ item.totalPayAmount.toFixed(2) }}</div>
          </div>

          <div style="margin-top:20px;height:10px;width:95%;border-top: 2px dashed black;" />
          <div style="height:20px;width:95%;border-top: 2px dashed black;" />

          <div style="position: relative;height: 15px">
            <div class="positionLeft">交易時間:</div>
            <div style="position: absolute; left: 30%;">{{ item.paymentTime }}</div>
          </div>
          <div style="position: relative;height: 30px">
            <div class="positionLeft">交易付款:</div>
            <div style="position: absolute; left: 30%; width: 70%;height: 30px">
              <div style="position: relative">
                <span>{{ item.payType }}</span>
                <span class="positionRight">{{ item.payTotalAmount }}</span>
              </div>
              <div style="position: relative">
                <span v-if="item.otherPayTotalAmount!==0">{{ item.otherPayType }}</span>
                <span v-if="item.otherPayTotalAmount!==0" class="positionRight">{{ item.otherPayTotalAmount }}</span>
              </div>
            </div>
          </div>

          <div v-if="item.returnAmount" style="position: relative;height: 15px">
            <div class="positionLeft">退款:</div>
            <div class="positionRight">{{ item.returnAmount }}</div>
          </div>
          <div style="margin-top:10px;height:10px;width:95%;border-top: 2px dashed black;" />
          <div style="position: relative;height: 10px">
            <div class="positionLeft">總產品數量</div>
            <div class="positionRight">{{ item.productNumber }}</div>
          </div>
          <div style="margin-top:10px;font-size: 16px;font-weight: 900;text-align: center">多謝惠顧! THANK YOU!</div>
          <div style="text-align: center">
            <vue-barcode
              v-if="item.orderSn"
              :value="item.orderSn"
              :options="{ height:30,background:'rgba(255,255,255,0)'}"
            >訂單編號
            </vue-barcode>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="messageVisible"
      title="发送站内信"
      width="1200px"
    >
      <el-form ref="form" :model="mesForm" :rules="rules" label-width="100px">
        <el-col :span="24">
          <el-form-item label="标题">
            <el-input v-model="mesForm.title" style="width: 450px;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="msgContent">
            <tinymce ref="tinymce" v-model="mesForm.msgContent" :width="900" :height="300" />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="messageVisible = false">取消</el-button>
        <el-button type="primary" @click="sendMessage">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudOrder from '@/api/oms/order'
import mallSet from '@/api/sms/mallSet'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import dateRangePicker from '@/components/DateRangePicker'
import { downloadFile } from '@/utils'
import html2Canvas from 'html2canvas'
import JSPDF from 'jspdf'
import { parseTime } from '@/utils'
import VueBarcode from '@xkeshi/vue-barcode'
import Tinymce from '@/components/Tinymce'
import crudMemberMessage from '@/api/msg/memberMessage'

const defaultForm = {
  autoConfirmDay: 0,
  billContent: null,
  billHeader: null,
  billReceiverEmail: null,
  billReceiverPhone: null,
  billType: 0,
  commentTime: null,
  confirmStatus: 0,
  couponAmount: null,
  couponId: null,
  deleteStatus: 0,
  deliveryCompany: null,
  deliverySn: null,
  deliveryTime: null,
  discountAmount: null,
  freightAmount: null,
  growth: 0,
  integration: 0,
  integrationAmount: null,
  memberId: null,
  memberUsername: null,
  note: null,
  orderSn: null,
  orderType: 0,
  payAmount: null,
  payType: 0,
  paymentTime: null,
  promotionAmount: null,
  promotionInfo: null,
  receiveTime: null,
  receiverCity: null,
  receiverDetailAddress: null,
  receiverName: null,
  receiverPhone: null,
  receiverPostCode: null,
  receiverProvince: null,
  receiverRegion: null,
  sourceType: 0,
  status: 0,
  totalAmount: null,
  useIntegration: 0,
  orderStatus: 0,
  preSale: false
}
const message = {
  title: null,
  msgContent: null,
  pushType: 3
}
export default {
  name: 'Order',
  components: { pagination, crudOperation, dateRangePicker, rrOperation, VueBarcode, Tinymce },
  dicts: [
    'orderStatus',
    'manualOrder',
    'deliveryType',
    'orderMarkType',
    'paymentStatus',
    'true_false',
    'presellState',
    'payType',
    'pushType'],
  filters: {},
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '订单管理',
      url: 'order/pageList',
      sort: [],
      query: { preSale: 0, paymentStatus: 1 },
      crudMethod: { ...crudOrder },
      optShow: { reset: true }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'order:add'],
        edit: ['admin', 'order:edit'],
        updateDeliveryTime: ['admin', 'order:updateDeliveryTime'],
        delivery: ['admin', 'order:delivery'],
        complete: ['admin', 'order:complete'],
        printDocuments: ['admin', 'order:printDocuments'],
        updateOrderNote: ['admin', 'order:updateOrderNote'],
        flagComplaint: ['admin', 'order:flagComplaint'],
        preSalArrival: ['admin', 'order:preSalArrival']

      },
      rules: {},
      mesForm: Object.assign({}, message),
      messageVisible: false,
      updateDeliveryTimeVisible: false,
      updateDeliveryTime: '',
      updateOrderNote: '',
      deliveryTimeOptions: [],
      updateDeliveryTimeSetting: { value: 'value', label: 'value' },
      selfPickVisible: false,
      selfPickTime: '',
      printOrder: [],
      modelEndDate: [parseTime(new Date().setMonth((new Date().getMonth() - 1)), '{y}-{m}-{d} {h}:{i}:{s}'), parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')]
    }
  },
  computed: {},

  created() {
    mallSet.getMallSet().then(res => {
      this.mallSet = res.data
    })
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    orderDetails(orderId) {
      this.$router.push({ path: 'orderDetails/' + orderId, query: { id: orderId }})
    },
    updateDelivery(sel) {
      const id = sel[0].id
      const date = this.updateDeliveryTime[0]
      const timeSlot = this.updateDeliveryTime[1]
      crudOrder.updateDeliveryTime({ orderId: id, date: date, timeSlot: timeSlot }).then(res => {
        if (res.code === 0) {
          this.updateDeliveryTime = ''
          this.updateDeliveryTimeVisible = false
          this.crud.refresh()
        }
        this.$notify({
          title: '成功',
          message: res.message,
          type: 'success'
        })
      })
    },
    getSelectIds(sel) {
      return sel.map(item => {
        return item.id
      })
    },
    showUpdateDeliveryTime(sel) {
      const id = sel[0].id
      mallSet.getDeliveryTime({ orderId: id }).then(res => {
        const times = res.data
        const date = []
        Object.keys(times).forEach((item, index) => {
          date.push({ value: item, children: [] })
          times[item].forEach(childrenItem => {
            date[index].children.push({ value: childrenItem })
          })
        })
        this.deliveryTimeOptions = date
      })
      this.updateDeliveryTimeVisible = true
    },
    delivery(ids) {
      crudOrder.delivery({ orderIds: ids }).then(res => {
        this.crud.refresh()
        this.$notify({
          title: '成功',
          message: res.message,
          type: 'success'
        })
      })
    },
    complete(sel) {
      this.$confirm('是否完成選中訂單?', '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.getSelectIds(sel)
        crudOrder.complete({ orderIds: ids }).then(res => {
          this.crud.refresh()
          this.$notify({
            title: '成功',
            message: res.message,
            type: 'success'
          })
        })
      })
    },
    onePrintDocuments(row) {
      const ids = [row.id]
      crudOrder.printOrder({ orderIds: ids }).then(res => {
        if (res.code === 0) {
          this.printOrder = res.data
          this.$nextTick(() => {
            // 渲染完毕再执行这个，所以才能没有延时的更改
            this.printPdf(row.orderSn, 0)
            this.delivery(ids)
          })
        }
      })
    },

    printDocuments(sel) {
      const ids = this.getSelectIds(sel)
      crudOrder.printOrder({ orderIds: ids }).then(res => {
        if (res.code === 0) {
          this.printOrder = res.data
          this.$nextTick(() => {
            // 渲染完毕再执行这个，所以才能没有延时的更改
            sel.forEach((item, index) => {
              this.printPdf(item.orderSn, index)
              this.delivery(ids)
            })
          })
        }
      })
    },

    selTagType(type) {
      switch (type) {
        case 0:
          return 'warning'
        case 1:
          return ''
        case 2:
          return 'success'
        case 3:
          return 'danger'
        case 4:
          return ''
      }
    },
    flagComplaint(sel) {
      this.$confirm('确认对选中订单標記為投訴訂單?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.getSelectIds(sel)
        crudOrder.flagComplaint({ orderIds: ids }).then(res => {
          this.crud.refresh()
          this.$notify({
            title: '成功',
            message: res.message,
            type: 'success'
          })
        })
      })
    },
    exportDeliveryOrder(sel) {
      const ids = this.getSelectIds(sel)
      crudOrder.exportDeliveryOrder({
        orderIds: ids,
        startDate: this.modelEndDate[0],
        endDate: this.modelEndDate[1]
      }).then(res => {
        if (res.code !== undefined && res.code !== 0) {
          this.$notify({
            title: '失敗',
            message: res.message,
            type: 'error'
          })
          return
        }
        downloadFile(res, this.crud.title + '数据', 'xlsx')
      })
    },

    printPdf(orderSn, index) {
      const id = '#pdfWrap' + index
      const pdfDom = document.querySelector(id) // 这里绑定你要转换的页面
      pdfDom.style.background = '#FFFFFF'
      html2Canvas(pdfDom, {
        // 开始截图,这里可以设置一些截图时的属性
        logging: false,
        allowTaint: true,
        taintTest: false,
        useCORS: true,
        dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
        scale: 4 // 按比例增加分辨率
      }).then((canvas) => {
        // 开始将图片转换为PDF
        const pdf = new JSPDF('p', 'mm', [80, 300]) // A4纸，纵向
        const ctx = canvas.getContext('2d')
        const a4w = 80
        const a4h = 300 // A4大小，210mm x 297mm，四边各保留20mm的边距，显示区域170x257
        const imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
        let renderedHeight = 0
        while (renderedHeight < canvas.height) {
          const page = document.createElement('canvas')
          page.width = canvas.width
          page.height = Math.min(imgHeight, canvas.height - renderedHeight)// 可能内容不足一页

          // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
          page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
          // 添加图像到页面，保留10mm边距
          pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 1, 1, a4w, Math.min(a4h, a4w * page.height / page.width))
          renderedHeight += imgHeight
          if (renderedHeight < canvas.height) {
            pdf.addPage()
          }// 如果后面还有内容，添加一个空页
          // delete page;
        }
        // 下载pdf
        // const pdfName = orderSn + '.pdf'
        // pdf.save(pdfName)
        // 新窗口打开pdf
        pdf.output('dataurlnewwindow')
      })
    },

    preSalArrival(sel) {
      this.$confirm('是否完成選中預售訂單到貨?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.getSelectIds(sel)
        crudOrder.preSaleArrival({ orderIds: ids }).then(res => {
          this.crud.refresh()
          this.$notify({
            title: '成功',
            message: res.message,
            type: 'success'
          })
        })
      })
    },

    payType(arr) {
      let payType = ''
      arr.forEach(item => {
        const name = this.dict.label.payType[item]
        payType = `${payType} ${name}`
      })
      return payType
    },
    addOffLineOrder() {
      this.$router.push({ path: 'addOfflineOrder' })
    },
    isRed({ row, rowIndex }) {
      if (row.orderStatus === 1) {
        return {
          color: '#ff0000'
        }
      }
    },
    sendMessage() {
      const memberIds = this.crud.selections.map(item => {
        return item.memberId
      })
      crudMemberMessage.add({ memberIds: memberIds, ...this.mesForm }).then(res => {
        this.$notify({
          title: res.code === 0 ? '成功' : '失败',
          message: res.message,
          type: res.code === 0 ? 'success' : 'error'
        })
        if (res.code === 0) {
          this.crud.refresh()
          this.messageVisible = false
        }
      })
    },
    sortChange(column) {
      const sortColumn = column.prop
      if (column.order === 'ascending') {
        this.crud.sort = [sortColumn + ':asc']
      }
      if (column.order === 'descending') {
        this.crud.sort = [sortColumn + ':desc']
      }
      this.crud.refresh()
    }
  }
}
</script>

<style scoped lang="scss">

.dig {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  text-align: center;
}

.DeliveryTime {
  color: #409EFF;
}

.invoice {
  width: 100%;
  background: rgba(255, 255, 255, 0);
  padding: 0 10px;

  .invoiceImg {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    margin-top: 30px;
    margin-bottom: 20px;
    vertical-align: middle;
  }

  .titleText {
    font-size: 12px;
    margin-bottom: 5px;
  }

  .single {
    font-size: 26px;
  }

  .category {
    display: inline-block;
    width: 35%;
    text-align: center;
    font-size: 14px;
  }
}

.product {
  width: 150px;
}

.price {
  position: absolute;
  right: 0;
}

.positionRight {
  position: absolute;
  right: 0;
}

.positionLeft {
  position: absolute;
  left: 0;
}

.print {
  font-size: 12px;
  margin: 0 auto;
}
</style>
